package com.bawei.module_mine.ui

import android.content.Intent
import android.graphics.Color
import android.net.ConnectivityManager
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter

import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_common.manager.UserDataManager
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIActivity
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityUserBinding
import com.bawei.module_mine.http.intent.LoginIntent
import com.bawei.module_mine.http.state.LoginState
import com.bawei.module_mine.http.viewModel.LoginViewModel
import com.bawei.module_mine.model.AddAccountModel
import com.bawei.module_mine.model.Card
import com.hyphenate.EMCallBack
import com.hyphenate.EMConnectionListener
import com.hyphenate.chat.EMClient
import kotlinx.coroutines.launch


@Route(path = Router.PATH_MINE + "UserActivity")
class UserActivity : BaseMVIActivity() {

    private lateinit var viewModel: LoginViewModel
    private val binding by lazy {
        ActivityUserBinding.inflate(layoutInflater)
    }

    // 防重复点击
    private var isClicking = false

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]
    }

    override fun getLayoutRootView(): View = binding.root

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect {
                    when (it) {
                        is LoginState.Error -> {
                            Toast.makeText(this@UserActivity, it.error, Toast.LENGTH_SHORT).show()
                        }

                        LoginState.Idle -> {}
                        LoginState.Loading -> {}
                        is LoginState.Success -> {
                            Toast.makeText(this@UserActivity, "登录成功", Toast.LENGTH_SHORT).show()
                            startActivity(Intent(this@UserActivity, PhoneBookActivity::class.java))
                            ARouter.getInstance().build(Router.Ui.PHONE_BOOK_ACTIVITY).navigation()
                            LoggerUtils.d("TAG", AuthMMKV.token)
                            LoggerUtils.d("TAG", AuthMMKV.uId.toString())
                            
                            // 登录成功后初始化用户数据
                            UserDataManager.initUserData()

                            val card = Card(
                                accountid = 1,
                                banktype = "工商银行",
                                cardnum = 123456789,
                                createtime = "2024-06-01 12:00:00",
                                id = 0
                            )
                            val addAccountModel = it.data?.let { it1 ->
                                AddAccountModel(
                                    accountamount = 1000,
                                    cards = listOf(card),
                                    coinamount = 500,
                                    createtime = "2024-06-01 12:00:00",
                                    id = 0,
                                    userid = it1.id,
                                    wxaccount = "",
                                    zfbaccount = ""
                                )
                            }
                            addAccountModel?.let { it1 ->
                                LoginIntent.AddAccount(
                                    it1
                                )
                            }?.let { it2 -> viewModel.intents.trySend(it2) }
                        }

                        is LoginState.AddAccountSuccess -> {}
                        is LoginState.LikeSuccess -> {}
                        is LoginState.MineSuccess -> TODO()
                        is LoginState.QuickLoginSuccess -> TODO()
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect {
                    when (it) {
                        is LoginState.AddAccountSuccess -> {
                            Toast.makeText(this@UserActivity, "添加账户成功", Toast.LENGTH_SHORT)
                                .show()
                            LoggerUtils.d("UserActivity", it.data?.id.toString())
                            // 这里可以做跳转或刷新等操作
                        }
                        // ... 其他状态处理
                        is LoginState.Error -> {}
                        LoginState.Idle -> {}
                        LoginState.Loading -> {}
                        is LoginState.Success -> {}
                        is LoginState.LikeSuccess -> {}
                        is LoginState.MineSuccess -> TODO()
                        is LoginState.QuickLoginSuccess -> TODO()
                    }
                }
            }
        }
    }

    override fun handleState() {

        binding.buttonLogin.setOnClickListener {
            val phone = binding.phoneNumberEditText.text.toString().trim()
            val pwd = binding.passwordEditText.text.toString().trim()
            if (phone.isEmpty() || pwd.isEmpty()) {
                Toast.makeText(this@UserActivity, "请输入手机号和密码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            viewModel.intents.trySend(LoginIntent.Login(phone, pwd))

        }
        binding.tvNoPassword.setOnClickListener {
            if (!isClicking) {
                isClicking = true
                ARouter.getInstance().build(Router.Ui.WEB_ACTIVITY)
                    .withString("url", "https://accounts.qq.com/find/password?from=11")
                    .navigation()
                // 延迟重置点击状态
                binding.tvNoPassword.postDelayed({ isClicking = false }, 1000)
            }
        }
        binding.buttonBack.setOnClickListener {
            finish()
        }
        binding.tvHelp.setOnClickListener {
            if (!isClicking) {
                isClicking = true
                ARouter.getInstance().build(Router.Ui.HELP_ACTIVITY).navigation()
                binding.tvHelp.postDelayed({ isClicking = false }, 1000)
            }
        }


        initAgreementCLick()
    }

    private fun initAgreementCLick() {
        val tvAgreement = findViewById<TextView>(R.id.tv_agreement)
        val content = "登录则表明同意 用户协议 和 隐私协议"
        val spannableString = SpannableString(content)
        val userAgreementStart = content.indexOf("用户协议")
        val userAgreementEnd = userAgreementStart + "用户协议".length
        spannableString.setSpan(
            object : ClickableSpan() {
                override fun onClick(p0: View) {
                    if (!isClicking) {
                        isClicking = true
                        // 显示加载提示
                        Toast.makeText(this@UserActivity, "正在加载用户协议...", Toast.LENGTH_SHORT)
                            .show()
                        ARouter.getInstance().build(Router.Ui.WEB_ACTIVITY)
                            .withString(
                                "url",
                                "https://terms.alicdn.com/legal-agreement/terms/suit_bu1_unification/suit_bu1_unification202005142208_14749.html"
                            )
                            .navigation()
                        // 延迟重置点击状态
                        p0.postDelayed({ isClicking = false }, 2000)
                    }
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = Color.parseColor("#FF000000")
                }
            },
            userAgreementStart,
            userAgreementEnd,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        // 处理"隐私协议"点击
        val privacyAgreementStart = content.indexOf("隐私协议")
        val privacyAgreementEnd = privacyAgreementStart + "隐私协议".length
        spannableString.setSpan(
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    if (!isClicking) {
                        isClicking = true
                        // 显示加载提示
                        Toast.makeText(this@UserActivity, "正在加载隐私协议...", Toast.LENGTH_SHORT)
                            .show()
                        ARouter.getInstance().build(Router.Ui.WEB_ACTIVITY)
                            .withString(
                                "url",
                                "https://www.douyin.com/draft/douyin_agreement/douyin_agreement_privacy.html?id=6773901168964798477"
                            )
                            .navigation()
                        // 延迟重置点击状态
                        widget.postDelayed({ isClicking = false }, 2000)
                    }
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = Color.parseColor("#FF000000")
                }
            },
            privacyAgreementStart,
            privacyAgreementEnd,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        // 设置给 TextView
        tvAgreement.text = spannableString
        // 必须设置，否则点击事件不生效
        tvAgreement.movementMethod = LinkMovementMethod.getInstance()
    }


    
    private fun isNetworkAvailable(): Boolean {
        val connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }
}